<template>
  <div class="pwa-status">
    <!-- 离线状态提示 -->
    <Transition name="slide-down">
      <div v-if="!isOnline" class="offline-banner">
        <i class="fas fa-wifi-slash"></i>
        <span>当前处于离线模式</span>
        <el-button 
          type="text" 
          size="small" 
          @click="syncOfflineData"
          :loading="syncing"
        >
          {{ syncing ? '同步中...' : '重试连接' }}
        </el-button>
      </div>
    </Transition>

    <!-- 更新可用提示 -->
    <Transition name="slide-down">
      <div v-if="updateAvailable" class="update-banner">
        <i class="fas fa-download"></i>
        <span>发现新版本</span>
        <div class="update-actions">
          <el-button 
            type="text" 
            size="small" 
            @click="dismissUpdate"
          >
            稍后
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="applyUpdate"
            :loading="updating"
          >
            {{ updating ? '更新中...' : '立即更新' }}
          </el-button>
        </div>
      </div>
    </Transition>

    <!-- 安装提示 -->
    <Transition name="slide-up">
      <div v-if="isInstallable && showInstallPrompt" class="install-banner">
        <div class="install-content">
          <div class="install-icon">
            <i class="fas fa-mobile-alt"></i>
          </div>
          <div class="install-text">
            <h4>安装小智医疗</h4>
            <p>添加到主屏幕，获得更好的使用体验</p>
          </div>
          <div class="install-actions">
            <el-button 
              type="text" 
              size="small" 
              @click="dismissInstall"
            >
              取消
            </el-button>
            <el-button 
              type="primary" 
              size="small" 
              @click="installPWA"
              :loading="installing"
            >
              {{ installing ? '安装中...' : '安装' }}
            </el-button>
          </div>
        </div>
      </div>
    </Transition>

    <!-- 缓存使用情况（开发模式显示） -->
    <div v-if="isDev && showCacheInfo" class="cache-info">
      <div class="cache-header">
        <span>缓存使用情况</span>
        <el-button 
          type="text" 
          size="small" 
          @click="showCacheInfo = false"
        >
          <i class="fas fa-times"></i>
        </el-button>
      </div>
      <div class="cache-details">
        <div class="cache-usage">
          <span>已使用: {{ formatBytes(cacheUsage.used) }}</span>
          <span>可用: {{ formatBytes(cacheUsage.available) }}</span>
          <span>使用率: {{ cacheUsage.percentage }}%</span>
        </div>
        <el-progress 
          :percentage="cacheUsage.percentage" 
          :color="getCacheColor(cacheUsage.percentage)"
          :show-text="false"
          :stroke-width="4"
        />
        <div class="cache-actions">
          <el-button 
            type="text" 
            size="small" 
            @click="updateCacheUsage"
          >
            刷新
          </el-button>
          <el-button 
            type="text" 
            size="small" 
            @click="clearCache"
            :loading="clearing"
          >
            {{ clearing ? '清理中...' : '清理缓存' }}
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="showCacheInfo = false"
            class="exit-button"
          >
            <i class="fas fa-sign-out-alt"></i>
            退出
          </el-button>
        </div>
      </div>
    </div>

    <!-- 连接质量指示器 -->
    <div v-if="showConnectionInfo" class="connection-info">
      <div class="connection-indicator" :class="connectionClass">
        <i :class="connectionIcon"></i>
        <span>{{ connectionText }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { usePWA } from '../composables/usePWA'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  showConnectionInfo: {
    type: Boolean,
    default: true
  },
  autoHideInstall: {
    type: Boolean,
    default: true
  },
  installPromptDelay: {
    type: Number,
    default: 5000
  }
})

// PWA功能
const {
  isOnline,
  updateAvailable,
  isInstallable,
  cacheUsage,
  applyUpdate: pwaApplyUpdate,
  installPWA: pwaInstall,
  syncOfflineData: pwaSyncOfflineData,
  updateCacheUsage: pwaUpdateCacheUsage,
  clearCache: pwaClearCache,
  getConnectionInfo,
  isSlowConnection
} = usePWA()

// 本地状态
const showInstallPrompt = ref(false)
const showCacheInfo = ref(false)
const updating = ref(false)
const installing = ref(false)
const syncing = ref(false)
const clearing = ref(false)
const isDev = ref(import.meta.env.DEV)

// 计算属性
const connectionInfo = computed(() => getConnectionInfo())

const connectionClass = computed(() => {
  if (!isOnline.value) return 'offline'
  if (isSlowConnection()) return 'slow'
  return 'good'
})

const connectionIcon = computed(() => {
  if (!isOnline.value) return 'fas fa-wifi-slash'
  if (isSlowConnection()) return 'fas fa-wifi text-warning'
  return 'fas fa-wifi text-success'
})

const connectionText = computed(() => {
  if (!isOnline.value) return '离线'
  if (isSlowConnection()) return '网络较慢'
  
  const info = connectionInfo.value
  if (info) {
    return `${info.effectiveType.toUpperCase()}`
  }
  return '在线'
})

// 方法
const applyUpdate = async () => {
  updating.value = true
  try {
    await pwaApplyUpdate()
  } finally {
    updating.value = false
  }
}

const dismissUpdate = () => {
  updateAvailable.value = false
}

const installPWA = async () => {
  installing.value = true
  try {
    await pwaInstall()
    showInstallPrompt.value = false
  } finally {
    installing.value = false
  }
}

const dismissInstall = () => {
  showInstallPrompt.value = false
  // 记住用户选择，一段时间内不再显示
  localStorage.setItem('pwa-install-dismissed', Date.now().toString())
}

const syncOfflineData = async () => {
  syncing.value = true
  try {
    await pwaSyncOfflineData()
  } finally {
    syncing.value = false
  }
}

const updateCacheUsage = async () => {
  await pwaUpdateCacheUsage()
}

const clearCache = async () => {
  clearing.value = true
  try {
    await pwaClearCache()
  } finally {
    clearing.value = false
  }
}

const formatBytes = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getCacheColor = (percentage) => {
  if (percentage < 50) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

const checkInstallPromptVisibility = () => {
  if (!isInstallable.value) return
  
  // 检查是否最近被用户拒绝
  const dismissed = localStorage.getItem('pwa-install-dismissed')
  if (dismissed) {
    const dismissedTime = parseInt(dismissed)
    const daysSinceDismissed = (Date.now() - dismissedTime) / (1000 * 60 * 60 * 24)
    if (daysSinceDismissed < 7) { // 7天内不再显示
      return
    }
  }
  
  // 延迟显示安装提示
  if (props.autoHideInstall) {
    setTimeout(() => {
      showInstallPrompt.value = true
    }, props.installPromptDelay)
  } else {
    showInstallPrompt.value = true
  }
}

// 生命周期
onMounted(() => {
  // 检查是否显示安装提示
  checkInstallPromptVisibility()
  
  // 开发模式下显示缓存信息
  if (isDev.value) {
    setTimeout(() => {
      showCacheInfo.value = true
    }, 3000)
  }
})
</script>

<style scoped>
.pwa-status {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 9999;
  pointer-events: none;
}

.pwa-status > * {
  pointer-events: auto;
}

/* 离线状态横幅 */
.offline-banner {
  background: linear-gradient(135deg, #f56c6c, #e6a23c);
  color: white;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.offline-banner i {
  font-size: 16px;
}

/* 更新横幅 */
.update-banner {
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: white;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.update-actions {
  display: flex;
  gap: 8px;
}

/* 安装横幅 */
.install-banner {
  position: fixed;
  bottom: 20px;
  left: 20px;
  right: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  overflow: hidden;
}

.install-content {
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.install-icon {
  width: 48px;
  height: 48px;
  background: linear-gradient(135deg, #409eff, #67c23a);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.install-text {
  flex: 1;
}

.install-text h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.install-text p {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.install-actions {
  display: flex;
  gap: 8px;
}

/* 缓存信息 */
.cache-info {
  position: fixed;
  top: 20px;
  right: 20px;
  width: 280px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  overflow: hidden;
}

.cache-header {
  padding: 12px 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  font-size: 14px;
}

.cache-details {
  padding: 16px;
}

.cache-usage {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
  color: #606266;
}

.cache-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.exit-button {
  background: linear-gradient(135deg, #f56c6c, #e6a23c) !important;
  border: none !important;
  color: white !important;
  font-weight: 600;
  transition: all 0.3s ease;
}

.exit-button:hover {
  background: linear-gradient(135deg, #e6a23c, #f56c6c) !important;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.exit-button i {
  margin-right: 4px;
}

/* 连接信息 */
.connection-info {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.connection-indicator {
  background: white;
  padding: 8px 12px;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  transition: all 0.3s ease;
}

.connection-indicator.offline {
  background: #f56c6c;
  color: white;
  border-color: #f56c6c;
}

.connection-indicator.slow {
  background: #e6a23c;
  color: white;
  border-color: #e6a23c;
}

.connection-indicator.good {
  background: #67c23a;
  color: white;
  border-color: #67c23a;
}

/* 动画 */
.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.3s ease;
}

.slide-down-enter-from {
  transform: translateY(-100%);
  opacity: 0;
}

.slide-down-leave-to {
  transform: translateY(-100%);
  opacity: 0;
}

.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}

.slide-up-enter-from {
  transform: translateY(100%);
  opacity: 0;
}

.slide-up-leave-to {
  transform: translateY(100%);
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .install-banner {
    left: 10px;
    right: 10px;
    bottom: 10px;
  }
  
  .cache-info {
    top: 10px;
    right: 10px;
    left: 10px;
    width: auto;
  }
  
  .connection-info {
    bottom: 10px;
    right: 10px;
  }
  
  .install-content {
    padding: 12px;
  }
  
  .install-icon {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
  
  .install-text h4 {
    font-size: 14px;
  }
  
  .install-text p {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .offline-banner,
  .update-banner {
    padding: 6px 12px;
    font-size: 12px;
  }
  
  .update-actions {
    flex-direction: column;
    gap: 4px;
  }
}
</style>